package henu.graduation_design.onlineshop;

import henu.graduation_design.adapter.ProductStarAdapter;
import henu.graduation_design.tool.AnalyseProductStarJson;
import henu.graduation_design.util.JsonLoader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.KeyEvent;
import android.view.Window;
import android.widget.ListView;
import android.widget.Toast;

public class ProductStarActivity extends Activity {

	ListView starListView;
	
	private JsonLoader jsonLoader = new JsonLoader();
	List<HashMap<String, Object>> list;

	private void loadJson(final String url) {
		jsonLoader.getJsonArray(url, new JsonLoader.JsonArrayCallback() {
			public void jsonLoaded(JSONArray jsonArray) {
				List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
				AnalyseProductStarJson analyse = new AnalyseProductStarJson(jsonArray);
				try {
					list = analyse.getList();
				} catch (JSONException e) {
					Toast.makeText(getApplicationContext(),
							"解析category的json数据发生异常", Toast.LENGTH_LONG).show();
				}

				starListView.setAdapter(new ProductStarAdapter(
						ProductStarActivity.this, list));
			}
		});
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_product_star);
		
		starListView = (ListView) findViewById(R.id.product_star_listView);
		list = new ArrayList<HashMap<String, Object>>();
		
		try {
			String urlString = getString(R.string.url_star);
			loadJson(urlString);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			new AlertDialog.Builder(this)
					// .setIcon(R.drawable.services)
					.setTitle("注意")
					.setMessage("确定要退出吗？")
					.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
								}
							})
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									finish();
								}
							}).show();
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

}
